package com.hshoesmall.demo.controller;

import com.hshoesmall.demo.common.api.ApiResult;
import com.hshoesmall.demo.model.dto.ShoesUserLoginDTO;
import com.hshoesmall.demo.model.dto.ShoesUserRegisterDTO;
import com.hshoesmall.demo.model.entity.ShoesUser;
import com.hshoesmall.demo.service.ShoesUserService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


@RestController//在Spring中@RestController的作用等同于@Controller + @ResponseBody。
@RequestMapping("/user")//注解 @RequestMapping 可以用在类定义处和方法定义处。
public class ShoesUserConterller {
    @Resource//@Resource和@Autowired注解都是用来实现依赖注入的。只是@AutoWried按by type自动注入，而@Resource默认按byName自动注入。
    private ShoesUserService shoesUserService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ApiResult<Map<String, Object>> register(@Valid @RequestBody ShoesUserRegisterDTO dto) {
        //@Valid:用于验证注解是否符合要求，直接加在变量user之前，在变量中添加验证信息的要求，当不符合要求时就会在方法中返回message 的错误提示信息。
        //@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的)
        ShoesUser user = shoesUserService.executeRegister(dto);
        if (ObjectUtils.isEmpty(user)) {
            return ApiResult.failed("账号注册失败");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", user);
        return ApiResult.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult<Map<String, String>> login(ShoesUserLoginDTO dto) {
        String token = shoesUserService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("token", token);
        return ApiResult.success(map, "登录成功");
    }

}
